package com.awifi.demo.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @description: ToDo
 * @author: marin
 * @time: 2020/9/10 20:15
 */
public class NIOServer {
    public static void main(String[] args) throws Exception {
        ServerSocketChannel channel = ServerSocketChannel.open();
        Selector selector = Selector.open();
        channel.socket().bind(new InetSocketAddress(6666));
        channel.configureBlocking(false);

        channel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            if(selector.select(1000) == 0) {
                System.out.println("服务器等待1s，无连接");
                continue;
            }
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterators = selectionKeys.iterator();
            while (iterators.hasNext()) {
                SelectionKey key = iterators.next();
                //新的客户端连接
                if(key.isAcceptable()) {
                    System.out.println("----------");
                    SocketChannel accept = channel.accept();
                    accept.configureBlocking(false);
                    accept.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if (key.isReadable()) {
                    SocketChannel channel1 = (SocketChannel) key.channel();
                    ByteBuffer attachment = (ByteBuffer)key.attachment();
                    channel1.read(attachment);
                    System.out.println("客户端发过来的数据为："+new String(attachment.array()));
                }
                iterators.remove();
            }

        }


    }
}
